/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android app
 * Create Time: 16-2-19 下午5:31
 */

package com.lenovo.mso2o.ui.adapter;

import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.entity.g.Notification;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by hippo on 6/4/15.
 */

public class NotificationAdapter extends RecyclerView.Adapter<NotificationAdapter.ViewHolder> {
    List<Notification> notificationList = new ArrayList<>();
    OnNotificationSelectedListener listener;
    private Activity context;
    private String mYear;
    private String mMonth;
    private String mDay;
    private String mWay;
    private SimpleDateFormat    format   =   new SimpleDateFormat("HH:mm:ss");
    private SimpleDateFormat    formatter    =   new SimpleDateFormat("yyyy年MM月dd日    HH:mm:ss");
    private SimpleDateFormat    form   =   new SimpleDateFormat("yyyy-MM-dd");
    public NotificationAdapter(Activity ctx) {
        this.context = ctx;
    }

    public void setOnNotificationSelectedListener(OnNotificationSelectedListener listener) {
        this.listener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
        View view = inflater.inflate(R.layout.notification_item, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int i) {
        Notification notification = notificationList.get(i);
        holder.desc.setText(notification.getContent());
        if (MESSAGETYPE.NORMAL.equals(notification.getType()) || null == notification.getType() || notification.getUrl() == null || "".equals(notification.getType())) {
            holder.typeInfo.setText("");
            holder.image.setVisibility(View.GONE);
            holder.more.setVisibility(View.GONE);
        } else if(MESSAGETYPE.SLA_NOTIFY_ACTIVE_ORDER == notification.getType()){
            holder.image.setVisibility(View.GONE);
            holder.more.setVisibility(View.GONE);
        }else {
            holder.image.setVisibility(View.VISIBLE);
            holder.more.setVisibility(View.VISIBLE);
            Glide.with(context).load(notification.getUrl()).into(holder.image);
        }
        switch (notificationList.get(i).getType()){
            case MESSAGETYPE.GRAB_NOTIFY:
            case MESSAGETYPE.RECEIVE_NOTIFY:
                holder.typeImage.setImageResource(R.drawable.msg_new_order);
                break;
            case MESSAGETYPE.SLA_NOTIFY:
            case MESSAGETYPE.SLA_NOTIFY_ACTIVE_ORDER:
                holder.typeImage.setImageResource(R.drawable.msg_over_time_remind);
                break;
            case MESSAGETYPE.BILL_NUMBER:
                holder.typeImage.setImageResource(R.drawable.msg_sign);
                break;
        }
        //GRAB_NOTIFY
        //RECEIVE_NOTIFY
        //SLA_NOTIFY
        //BILL_NUMBER

        if(null == notification.getDate()) {
            holder.time.setText(form.format(new Date()));
        }else{
            if(isToday(form.format(notification.getDate()))){
                holder.time.setText(context.getString(R.string.today)+"    "+format.format(notification.getDate()));
            }else if(getTwoDay(formatter.format(notification.getDate()),formatter.format(new Date())) < 1){
                holder.time.setText(context.getString(R.string.yesterday)+"    "+format.format(notification.getDate()));
            }else if(isSameWeekDates(new Date(),notification.getDate())){
                String s = getWeekStr(formatter.format(notification.getDate()));
                String s1 = format.format(notification.getDate());
                holder.time.setText(s+"    "+s1);
            }else if(!isSameWeekDates(new Date(),notification.getDate())){
                holder.time.setText(formatter.format(notification.getDate()));
            }else{
                holder.time.setText(formatter.format(notification.getDate()));
            }
        }
    }

    @Override
    public int getItemCount() {
        return notificationList == null ? 0 : notificationList.size();
    }

    public void setListData(List<Notification> listData) {
        this.notificationList.clear();
        this.notificationList.addAll(listData);
    }

    public void addMoreData(List<Notification> moreData) {
        this.notificationList.addAll(moreData);
    }

    public List<Notification> getNotificationList() {
        return notificationList;
    }

    class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        @Bind(R.id.notification_type_image)
        ImageView typeImage;
        @Bind(R.id.notification_type_info)
        TextView typeInfo;
        @Bind(R.id.notification_describe_info)
        TextView desc;
        @Bind(R.id.notification_advertisement)
        ImageView image;
        @Bind(R.id.requirements_layout)
        RelativeLayout more;
        @Bind(R.id.notification_time)
        TextView time;
        @Bind(R.id.frame_container)
        FrameLayout frame;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            int position = getAdapterPosition() - 1;
            if (listener != null) {
                Notification notification = notificationList.get(position);
                if ("rich".equals(notification.getType()))
                    listener.onNotificationSelected(notification);
            }
        }
    }

    public static interface OnNotificationSelectedListener {
        void onNotificationSelected(Notification notification);
    }


    /**
     * 判断是否是当天
     */
    private boolean isToday(String date){
        Date currentTime = new Date();
        String dateString = form.format(currentTime);
        if(date.trim().equals(dateString.trim())){
            return  true;
        }
        return false;
    }


    /**
     * 判断二个时间是否在同一个周
     *
     * @param date1
     * @param date2
     * @return
     */
    public boolean isSameWeekDates(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(date1);
        cal2.setTime(date2);
        int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
        if (0 == subYear) {
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;
        } else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) {
            // 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;
        } else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;
        }
        return false;
    }

    /**
     * 根据一个日期，返回是星期几的字符串
     *
     * @param sdate
     * @return
     */
    public String getWeek(String sdate) {
        // 再转换为时间
        Date date = strToDate(sdate);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        // int hour=c.get(Calendar.DAY_OF_WEEK);
        // hour中存的就是星期几了，其范围 1~7
        // 1=星期日 7=星期六，其他类推
        return new SimpleDateFormat("EEEE").format(c.getTime());
    }
    public String getWeekStr(String sdate){
        String str = "";
        str = getWeek(sdate);
        if("1".equals(str)){
            str = context.getString(R.string.sunday);
        }else if("2".equals(str)){
            str = context.getString(R.string.monday);
        }else if("3".equals(str)){
            str = context.getString(R.string.tuesday);
        }else if("4".equals(str)){
            str = context.getString(R.string.wednesday);;
        }else if("5".equals(str)){
            str = context.getString(R.string.thursday);
        }else if("6".equals(str)){
            str = context.getString(R.string.friday);
        }else if("7".equals(str)){
            str = context.getString(R.string.saturday);
        }
        return str;
    }

    /**
     * 将短时间格式字符串转换为时间 yyyy-MM-dd
     *
     * @param strDate
     * @return
     */
    public Date strToDate(String strDate) {
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }
    /**
     * 得到二个日期间的间隔天数
     */
    public long getTwoDay(String sj1, String sj2) {
        long day = 0;
        try {
            Date date = form.parse(sj1);
            Date mydate = form.parse(sj2);
            day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
        } catch (Exception e) {
            return 2;
        }
        return day;
    }

    public static class MESSAGETYPE {
        public static final String NORMAL = "normal";
        public static final int GRAB_NOTIFY = 1;
        public static final int RECEIVE_NOTIFY = 2;
        public static final int SLA_NOTIFY = 3;
        public static final int BILL_NUMBER = 8;
        public static final int SLA_NOTIFY_ACTIVE_ORDER = -1;
    }
}

